package com.cbg.dg.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cbg.base.utils.CodeMsg;
import com.cbg.base.utils.SpringContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;
import java.util.Date;

/**
 * <pre></pre>
 * <small> 2018-12-26 | chenbing </small>
 */
public class JwtUtils {
    private static final Logger log= LoggerFactory.getLogger(JwtUtils.class);
    private static final JwtProperties jwtProperties;
    static {
        Environment env = SpringContextHolder.getBean(Environment.class);
        Binder binder = Binder.get(env);
        jwtProperties = binder.bind("mi.jwt", Bindable.of(JwtProperties.class)).get();
    }

    public static String sign(String userId){
        try{
            Date date = new Date(System.currentTimeMillis() + jwtProperties.getExpireTime());
            Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getSecret());
            return JWT.create().withClaim(jwtProperties.getPrimaryKey(),userId).withExpiresAt(date).sign(algorithm);
        }catch (Exception e){
            throw new RuntimeException(CodeMsg.SignFailed.getMsg());
        }
    }

    public static boolean verify(String token,String userId){
        try{
            Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getSecret());
            JWTVerifier verifier = JWT.require(algorithm).withClaim(jwtProperties.getPrimaryKey(), userId).build();
            verifier.verify(token);
            return true;
        }catch (Exception e){
            log.info("token签名校验失败:{}",token);
            return false;
        }
    }

    public static String getUserId(String token){
        try{
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(jwtProperties.getPrimaryKey()).asString();
        }catch (JWTDecodeException e){
            log.warn("token解码获取{}失败:{}",jwtProperties.getPrimaryKey(),token);
            return null;
        }
    }
}
